package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.utils.AgeCalculator;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * 入住Service业务层处理
 *
 * @author zs
 * @date 2025-09-30
 */
@Service
@Transactional
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }


    /**
     * 新增入住
     */
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //先判断老人是否入住(如果老人存在，而且是入住状态，程序不再走下去)
        LambdaQueryWrapper<Elder> elqw = new LambdaQueryWrapper<>();
        elqw.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elqw);
        if (elder == null) {
            //修改选中的床位状态
            LambdaUpdateWrapper<Bed> uqw = new LambdaUpdateWrapper<>();
            uqw.eq(Bed::getId, checkInApplyDto.getCheckInConfigDto().getBedId())
                    .set(Bed::getBedStatus, 1);
            bedMapper.update(null, uqw);
            //先查找床位信息，方便后续赋值
            Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());

            //存储老人信息
            Elder elder1 = new Elder();
            BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(), elder1);
            elder1.setBedId(bed.getId());
            elder1.setBedNumber(bed.getBedNumber());
            elderMapper.insert(elder1);

            //存储入住信息
            CheckIn checkIn = saveCheckIn(checkInApplyDto, elder1);

            //存储入住详细配置
            saveCheckInConfig(checkIn.getId(), checkInApplyDto);

            //存储合同表
            saveContract(elder1, checkInApplyDto);
        }

    }


    //保存合同表
    private void saveContract(Elder elder1, CheckInApplyDto checkInApplyDto) {
        //生成合同编号
        String s = "T" + CodeGenerator.generateContractNumber();
        Contract contract = new Contract();
        contract.setContractNumber(s);
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setElderId(Math.toIntExact(elder1.getId()));
        contract.setElderName(elder1.getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        if (LocalDateTime.now().isBefore(checkInApplyDto.getCheckInConfigDto().getStartDate())) {
            contract.setStatus(0);
        } else if (LocalDateTime.now().isAfter(checkInApplyDto.getCheckInConfigDto().getEndDate())) {
            contract.setStatus(2);
        } else {
            contract.setStatus(1);
        }
        contract.setSignDate(LocalDateTime.now());
        contractMapper.insert(contract);
    }

    //保存入住详细配置
    private void saveCheckInConfig(Long id, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(id);
        checkInConfig.setRemark(JSONArray.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkInConfigMapper.insert(checkInConfig);
    }

    //保存入住信息
    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder1) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(elder1, checkIn);
        checkIn.setElderId(elder1.getId());
        checkIn.setElderName(elder1.getName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 查询入住详情
     */
    @Override
    public CheckInDetailVo detail(Long id) throws JsonProcessingException {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        //根据入住id查询入住信息和配置信息，返回老人id
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectcheckInConfigById(checkIn.getId());
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());

        //查询老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        BeanUtils.copyProperties(elder,checkInElderVo);
        //根据birthday查询年龄
        String birthday = elder.getBirthday();
        int age = AgeCalculator.calculateAge(birthday);
        checkInElderVo.setAge(age);

        //家属信息
        String json = checkInConfig.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSONArray.parseArray(json, ElderFamilyVo.class);


        //根据老人id查询合同信息
        Contract contract = contractMapper.selectContract1ById(elder.getId());
        System.out.println( contract);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);
        return checkInDetailVo;
    }



}
